import ApiFetchers from "@/apis/api_fetchers"
import { useUserInfo } from "@/features/business/HomePage_deprecated"
import { pagePathAtom } from "@/features/business/HomePage_deprecated/atom"
import { useLoginAction } from "@/features/useSearchAction"
import kycRequiredMethods from "@/features_signal/kycRequiredMethods"
import { useSetAtom } from "jotai"
import { useCallback } from "react"
import { useNavigate } from "react-router-dom"
import { toast } from "react-toastify"

export function useEnterGame() {
    const { isLogin } = useUserInfo()

    const navigate = useNavigate()
    const setCachePath = useSetAtom(pagePathAtom)
    const { openModalToStep } = useLoginAction()

    const handleLogin = useCallback(() => {
        openModalToStep("login-otp-1")
    }, [openModalToStep])

    const enterGame = useCallback(
        async (code: string, clearPath?: boolean) => {
            const resp = await ApiFetchers.refGetGameLaunch({
                code,
            })
            if (resp.startsWith("http")) {
                // 清除要返回页面的记录
                if (clearPath) {
                    setCachePath({ homeCurrentPath: "" })
                }
                return navigate(`/game-page/${code}?game_url=${encodeURIComponent(resp)}`, {
                    state: {
                        from: location.pathname,
                    },
                })
            }
            if (resp.startsWith("data:text/html;charset=utf-8")) {
                // 清除要返回页面的记录
                if (clearPath) {
                    setCachePath({ homeCurrentPath: "" })
                }
                return navigate(`/game-page/${code}`, {
                    state: {
                        from: location.pathname,
                        content: resp,
                    },
                })
            }

            toast.error(resp || "error")
        },
        [navigate, setCachePath],
    )

    const handleEnterGame = useCallback(
        async (code: string, clearPath?: boolean) => {
            if (!isLogin) {
                return handleLogin()
            }
            kycRequiredMethods.execute("play", async () => {
                return enterGame(code, clearPath)
            })
        },
        [isLogin, handleLogin, enterGame],
    )

    return {
        handleEnterGame,
    }
}
